package com.tater.service;

import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.rpc.*;
import org.omg.CORBA.SetOverrideType;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * group 指定了过滤器的使用范围为 消费端
 */
@Activate(group = {CommonConstants.CONSUMER})
public class TPMonitorFilter implements Filter,Runnable {


    Map<String,List<MonitorMethod>> map=new ConcurrentHashMap<>();


    public TPMonitorFilter() {
        try {
            ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
            executor.scheduleAtFixedRate(this,5,5, TimeUnit.SECONDS);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
        long  startTime = System.currentTimeMillis();
        MonitorMethod method=new MonitorMethod();
        method.setMethodName(invocation.getMethodName());
        Result invoke = invoker.invoke(invocation);
        long  endTime = System.currentTimeMillis();
        method.setEndTime(endTime);
        method.setRunTime(endTime-startTime);
        List<MonitorMethod> list=new ArrayList<>();
        if (map.containsKey(method.getMethodName())){
            list = map.get(method.getMethodName());
        }
        list.add(method);
        map.put(method.getMethodName(),list);
        return invoke;
    }

    @Override
    public void run() {
        MonitorUtil.printTPInfo(map);
    }
}
